package com.household.domain.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.household.domain.enums.RoleEnum;
import com.household.domain.enums.SexEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Created By wanzhen
 * 2023. 2023/3/25. 10:33
 */

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User implements UserDetails {

//    雪花算法生成ID
    @TableId(type = IdType.ASSIGN_UUID)
    private String id;
//    用户名
    private String username;
//    密码
    private String password;

//    用户角色
    private RoleEnum role;

//    用户性别
    private SexEnum sex;

//    真实姓名
    private String realName;

//    身份证号
    private String idCard;

//    手机号
    private String tel;

    /**
     * 是否启用
     * 1：启用；0：禁用
     */
    private Integer hasEnable;

//    乐观锁
    @Version
    private Integer version;

    private String companyId;

    /**
     * 解冻时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime lockDate;

    @TableField(fill = FieldFill.INSERT)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createDate;

    @TableField(fill = FieldFill.UPDATE)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime updateDate;

//    逻辑删除
    @TableLogic
    private Integer isDeleted;





    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return new ArrayList<GrantedAuthority>(){{
            add(new SimpleGrantedAuthority(getRole().getName()));
        }};
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否未冻结
     */
    @Override
    public boolean isAccountNonLocked() {
        if(this.lockDate == null) {
            return true;
        }
//        当前时间与解冻时间比较
        return LocalDateTime.now().isAfter(this.lockDate);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否启用
     */
    @Override
    public boolean isEnabled() {
        return this.hasEnable==1;
    }
}
